//LoginFilter.java
package org.example.demo3.filter;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import jakarta.servlet.annotation.WebFilter;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component //告诉spring生成一个bean，Component是Controller，Service，Mapper的总称
@WebFilter("/") //对所有的请求进行过滤
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpSession session = request.getSession();
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取请求路径，用于判断该用户是否去登录页面
        String path = request.getRequestURI();
        // 放行静态资源
        if (path.startsWith("/bootstrap/") || path.startsWith("/css/") || path.startsWith("/js/")) {
            filterChain.doFilter(request, response);
            return;
        }

        if(path.contains("login")){
            filterChain.doFilter(request,response);
        } else if (session.getAttribute("username") != null) {
            filterChain.doFilter(request,response);
        }else{
            response.sendRedirect("/login");
        }
    }

}
